#! /usr/bin/env python
#coding=utf-8
import os
import time
import numpy as np
from ctypes import *

class USBI2C():
    ch341 = windll.LoadLibrary("CH341DLLA64.dll")
    def __init__(self, usb_dev = 0, i2c_dev = 0x80):
        self.usb_id   = usb_dev
        self.dev_addr = i2c_dev
        if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
            USBI2C.ch341.CH341SetStream(self.usb_id, 0x82)
            USBI2C.ch341.CH341CloseDevice(self.usb_id)
        else:
            print("USB CH341 Open Failed!")

    def read(self, data_addr):
        if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
            
            rec  = (c_ubyte * 2)()
            ibuf = (c_ubyte * 2)()
            rec[0] = self.dev_addr
            rec[1] = data_addr & 0xff
            USBI2C.ch341.CH341StreamI2C(self.usb_id, 2, rec, 2, ibuf)
            USBI2C.ch341.CH341CloseDevice(self.usb_id)
            
            return ibuf
        else:
            print("USB CH341 Open Failed!")
            return 0

    def write(self):
        if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
            cmd = (c_byte * 6)()
            ibuf = (c_byte * 1)()
            
            cmd[0] = self.dev_addr
            cmd[1] = 0x5a & 0xff
            cmd[2] = 0x05 & 0xff
            cmd[3] = 0x00 & 0xff
            cmd[4] = 0x01 & 0xff
            cmd[5] = 0x60 & 0xff

            USBI2C.ch341.CH341StreamI2C(self.usb_id, 6, cmd, 0, ibuf)
            USBI2C.ch341.CH341CloseDevice(self.usb_id)
        else:
            print("USB CH341 Open Failed!")


if __name__ == "__main__":
    cmd=np.arange = (0x5a,0x05,0x00,0x01,0x60)
    while True:
        q = USBI2C()
        # q.write()
        rec =q.read(0x00)
        print("read:")
        for b in rec:
            print(b)
        # get hex from 2 bytes
        print(hex(rec[0] << 8 | rec[1]))
        # print(rec)
        # dist    =((rec[2]&0xff)+(rec[3]&0xff)*256)
        # strengh =((rec[4]&0xff)+(rec[5]&0xff)*256)
        # temp    =((rec[6]&0xff)+(rec[7]&0xff)*256)/8-256
        # print("Dist:",dist,"Strengh:",strengh,"Temp:",temp)
       # print(cmd,hex)
        # print('0x%x'%cmd[1])     
        time.sleep(0.05) #50ms
        exit()
